package com.woniuxy.rbac.shiro;

import com.woniuxy.rbac.entity.Member;
import com.woniuxy.rbac.entity.Perm;
import com.woniuxy.rbac.entity.User;
import com.woniuxy.rbac.service.PermService;
import com.woniuxy.rbac.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class SysRealm extends AuthorizingRealm {
    @Autowired
    private PermService permService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取用户的所有权限
        Member member = (Member) principals.getPrimaryPrincipal();
        //member.getId()
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        List<Perm> perms = permService.getPerms();
        for (Perm perm : perms) {
            simpleAuthorizationInfo.addStringPermission(perm.getCode());
        }
        return simpleAuthorizationInfo;
    }

    @Autowired
    private UserService userService;

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        SysToken t = (SysToken) token;
        User user = userService.login(t.getPrincipal().toString());
        if (user == null) {
            throw new UnknownAccountException("账号不存在");
        }
        ByteSource byteSource=ByteSource.Util.bytes(user.getAccount());
        return new SimpleAuthenticationInfo(user, user.getPassword(), byteSource,getName());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof SysToken;
    }
}
